<template>
  <UniPopup
    ref="selectIndustryPopup"
    type="bottom"
    borderRadius="32rpx 32rpx 0 0"
    backgroundColor="#FFF"
    :isMaskClick="false"
    :z-index="999"
    @maskClick="handleMaskClick"
  >
    <view class="popup-content">
      <view class="px-16 pb-8">
        <view class="fz-16 py-12">
          <text>选择行业</text>
        </view>
        <UniSearchBar
          v-model="searchValue"
          placeholder="请输入搜索内容"
          radius="35"
          cancelButton="auto"
          @confirm="searchFnc"
          @cancel="restFnc"
          @clear="restFnc"
        />
      </view>
      <scroll-view
        class="scroll-view"
        scroll-y
        :enable-flex="true"
        scroll-with-animation
        scroll-anchoring
        :enhanced="true"
        :show-scrollbar="false"
      >
        <template v-for="(item, index) in localdataTree" :key="item.value">
          <view>
            <view class="px-16 py-12 disFlxAC" @click="handleItemClick(item)">
              <view class="flex-1">
                <view class="fz-14 fw-7">
                  <text>{{ item.text }}</text>
                </view>
                <view class="fz-12 ov-1 mt-4">
                  <text>{{ item.desc }}</text>
                </view>
              </view>
              <view class="ml-16 flex-shrink-0 disFlxAC">
                <view v-if="item.selectedCount" class="disFlxCC w-22 h-22 count-tag fz-12">
                  <text>{{ item.selectedCount }}</text>
                </view>
                <text
                  class="ali-icon fz-24 ml-8"
                  :style="{
                    transition: '.3s',
                    transform: item.isOpen ? 'rotateZ(-180deg)' : 'rotateZ(0deg)',
                  }"
                >
                  &#xe67e;
                </text>
              </view>
            </view>
            <view
              class="children-container"
              :style="{ gridTemplateRows: item.isOpen ? '1fr' : '0fr' }"
            >
              <view class="children-list">
                <template v-for="v in item.children" :key="v.value">
                  <view
                    v-if="v.isShow"
                    class="pl-32 pr-16 py-12 disFlxJS"
                    @click.stop="handleChildrenItemClick(v, index)"
                  >
                    <view class="flex-1 ov-1">
                      <text>{{ v.text }}</text>
                    </view>
                    <view>
                      <text v-if="hasSelected(v)" class="ali-icon fz-20" style="color: #2878ff">
                        &#xe693;
                      </text>
                      <text v-else class="ali-icon fz-20" style="color: #969799">&#xe690;</text>
                    </view>
                  </view>
                </template>
              </view>
            </view>
          </view>
        </template>
      </scroll-view>
      <view>
        <view class="px-16 py-8 disFlxAC">
          <view class="fz-14 flex-shrink-0 py-2">
            <text :style="{ opacity: selectedList.length ? 1 : 0 }">已选：</text>
          </view>
          <scroll-view
            class="flex-1 tag-list"
            scroll-x
            :enable-flex="true"
            scroll-with-animation
            scroll-anchoring
            :enhanced="true"
            :show-scrollbar="false"
          >
            <view class="disFlxAC">
              <template v-for="(v, i) in selectedList" :key="i">
                <view
                  class="selected-tag br-2 px-6 fz-14 mx-5 py-2 disFlxAC"
                  @click="handleDelSelected(v)"
                >
                  <text>{{ getValueText(v) }}</text>
                  <text class="ali-icon fz-14 ml-4">&#xeaf2;</text>
                </view>
              </template>
            </view>
          </scroll-view>
        </view>
        <view class="px-16 pt-10" :class="{ 'pb-10': !isNewIphone() }">
          <TButton text="确定" type="primary" @click="handleSubmit" />
        </view>
      </view>
    </view>
  </UniPopup>
</template>

<script setup lang="ts">
  import UniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
  import UniSearchBar from '@/uni_modules/uni-search-bar/components/uni-search-bar/uni-search-bar.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { ref, type PropType, getCurrentInstance, watch, watchEffect, useAttrs } from 'vue';
  import type { TreeDataItem } from './types';
  import type { Localdata } from '../Form/types';
  import { isArray, isNewIphone, isNullOrUnDef } from '@/utils/is';
  import { propTypes } from '@/utils/propTypes';
  import { intersection, isNumber } from 'lodash-es';
  import { memberTypeGetList } from '@/api/membership';
  import { localDataMapping } from '../Form/hooks/useForm';
  import type { MemberTypeGetListItem } from '@/api/membership/types';

  const props = defineProps({
    show: propTypes.bool.def(false),
    isApiData: propTypes.bool.def(false),
    /**
     *
     * @type industryId 机构行业数据
     * @type orgIndustryId 运营平台行业数据
     * @description 源数据字段
     */
    sourcesKey: {
      type: String as PropType<'industryId' | 'orgIndustryId'>,
      default: 'industryId',
    },
    localdata: {
      type: Array as PropType<Localdata[]>,
      default: () => [],
    },
    selected: {
      type: Array as PropType<number[] | string[]>,
      default: () => [],
    },
    resultKey: {
      type: String as PropType<keyof MemberTypeGetListItem>,
      default: 'id',
    },
  });

  const emits = defineEmits(['submit', 'update:show']);

  watch(
    () => props.show,
    (val) => {
      val ? handleOpen() : handleClose();
    },
  );

  function handleOpen() {
    if (isArray(props.selected)) {
      let list = props.selected;
      localdataTree.value.forEach((v) => {
        const cIds = v.children.map((cv) => cv.value);
        v.selectedCount = intersection(cIds, list).length;
      });
      selectedList.value = list;
    }
    (_this?.refs['selectIndustryPopup'] as any).open();
  }

  function handleClose() {
    (_this?.refs['selectIndustryPopup'] as any).close();
    searchValue.value = '';
  }

  const _this = getCurrentInstance();

  const localdataTree = ref<TreeDataItem[]>([]);
  const localdata = ref<Localdata[]>([]);
  const selectedList = ref<(number | string)[]>([]);

  if (props.isApiData) {
    memberTypeGetList([props.sourcesKey]).then((res) => {
      const data = localDataMapping(res[props.sourcesKey], {
        label: 'name',
        value: props.resultKey,
      });
      localdata.value = data;
      localdataTree.value = arrayToTree(data);
    });
  } else
    watchEffect(() => {
      const data = props.localdata as Localdata[];
      if (isArray(data) && data.length) {
        localdata.value = data;
        localdataTree.value = arrayToTree(data);
      }
    });
  {
  }

  function arrayToTree(data: Localdata[], parentCode: string | null = null) {
    const result: TreeDataItem[] = [];
    for (const item of data) {
      if (item.parentCode === parentCode) {
        const children = arrayToTree(data, item?.code as string);

        const treeDataItem: TreeDataItem = {
          isOpen: false,
          isShow: true,
          selectedCount: 0,
          ...item,
          children: children,
        };
        result.push(treeDataItem);
      }
    }
    return result;
  }

  function getValueText(id: number | string) {
    return localdata.value.find((v) => v.value == id)?.text;
  }

  function handleItemClick(item: TreeDataItem) {
    item.isOpen = !item.isOpen;
  }

  function hasSelected(item: Localdata) {
    return selectedList.value.some((v) => v == item.value);
  }

  function handleChildrenItemClick(item: Localdata, parentIndex: number) {
    const value = item.value as number;
    if (hasSelected(item)) {
      handleDelSelected(value, parentIndex);
    } else {
      localdataTree.value[parentIndex].selectedCount++;
      selectedList.value.unshift(value);
    }
  }

  function handleDelSelected(value: number | string, parentIndex?: number) {
    if (isNullOrUnDef(parentIndex)) {
      const parentCode = localdata.value.find((v) => v.value == value)?.parentCode;
      parentIndex = localdataTree.value.findIndex((v) => v.code == parentCode);
    }
    localdataTree.value[parentIndex].selectedCount--;
    selectedList.value = selectedList.value.filter((v) => v !== value);
  }

  function handleMaskClick() {
    emits('update:show', false);
  }

  function handleSubmit() {
    emits('update:show', false);
    emits('submit', selectedList.value);
  }

  const searchValue = ref('');
  function searchFnc(e: { value: string }) {
    localdataTree.value.forEach((v) => {
      let isExist = false;
      v.children.forEach((cv) => {
        const includesValue = cv.text.includes(e.value);
        if (includesValue) {
          isExist = true;
          v.isOpen = true;
        }
        cv.isShow = includesValue;
      });
      if (!isExist) v.isOpen = false;
    });
  }

  function restFnc() {
    localdataTree.value.forEach((v) => {
      v.isOpen = true;
      v.children.forEach((cv) => {
        cv.isShow = true;
      });
    });
  }
</script>

<style lang="scss" scoped>
  .popup-content {
    color: #333;
    .scroll-view {
      width: 100%;
      height: 60vh;
      box-sizing: border-box;
      .count-tag {
        color: #2878ff;
        background-color: #d0f7ff;
        border-radius: 50%;
      }
      .children-container {
        display: grid;
        grid-template-rows: 0fr;
        transition: all 0.3s;
        overflow: hidden;
        .children-list {
          background-color: #f2f3f5;
          min-height: 0;
        }
      }
    }

    .tag-list {
      width: 400rpx;

      .selected-tag {
        background-color: #f2f3f5;
        white-space: nowrap;
      }
    }
  }
</style>
